#!/bin/bash

#全局脚本
source /etc/profile;

##########################################
# 1. 从pid文件读取
# 2. 若pid存在, 则exit 0.
# 3. 若pid不存在, 则启动相应的命令, 并将进程号记入
#
##########################################

if [[ $# -ne 1 ]];then
	echo "Usage: guard <command_script>";
	exit 201;
fi
declare fpid=/tmp/guardbg/$(echo -n "$@"|md5sum|awk '{print $1}');
declare pid=0;
if [[ -f ${fpid} ]];then
	read pid < ${fpid};
	ps -p ${pid:-0} > /dev/null
	if [[ $? -eq 0 ]];then
		echo "previous process still running...${pid}, $@"
		exit 200;
	fi
fi

if [[ ! -d $(dirname ${fpid}) ]];then
	mkdir -p $(dirname ${fpid});
fi
eval "$@";
echo $! > ${fpid}
exit 0;
